import SecureLS from "secure-ls";
import CryptoJS from "crypto-js";

// 读取配置文件的LS密钥
const SECRET_KEY = import.meta.env.VITE_LS_ENCRYPITION_SECRET;
const ls = new SecureLS({
  isCompression: false,
  encodingType: "aes",
  encryptionSecret: SECRET_KEY,
});

if (!SECRET_KEY) {
  console.warn(
    "VITE_LS_ENCRYPITION_SECRET is not set, using default key. This is not secure for production."
  );
}
// 本地存储
export const localSecretStorage = {
  setItem: (key, value) => {
    ls.set(key, value);
  },
  getItem: (key) => {
    return ls.get(key);
  },
  removeItem: (key) => {
    ls.remove(key);
  },
  has: (key) => {
    return ls.get(key) !== null && ls.get(key) !== undefined;
  },
  set: (key, value) => {
    ls.set(key, value);
  },
  get: (key) => {
    return ls.get(key);
  },
  keys: () => {
    return ls.getAllKeys();
  },
  all: () => {
    let data = {};
    let keys = ls.getAllKeys();
    keys.forEach((key) => {
      data[key] = ls.get(key);
    });
    return data;
  },
  size: () => {
    return ls.getAllKeys().length;
  },
  rem: (key) => {
    ls.remove(key);
  },
  clear: () => {
    ls.removeAll();
  },
};

// 会话存储
export const sessionSecretStorage = {
  setItem: (key, value) => {
    ls.set(key, value);
  },
  getItem: (key) => {
    return ls.get(key);
  },
  removeItem: (key) => {
    ls.remove(key);
  },
  set: (key, value) => {
    try {
      const str = JSON.stringify(value);
      const encrypted = CryptoJS.AES.encrypt(str, SECRET_KEY).toString();
      sessionStorage.setItem(key, encrypted);
    } catch (e) {
      console.error("[SessionStorage] Set failed:", e);
    }
  },

  get: (key) => {
    try {
      const encrypted = sessionStorage.getItem(key);
      if (!encrypted) return null;
      const bytes = CryptoJS.AES.decrypt(encrypted, SECRET_KEY);
      const data = bytes.toString(CryptoJS.enc.Utf8);
      return JSON.parse(data);
    } catch (e) {
      console.warn("[SessionStorage] Get failed for key:", key, e);
      return null;
    }
  },

  all: () => {
    const data = {};
    for (let i = 0; i < sessionStorage.length; i++) {
      const key = sessionStorage.key(i);
      data[key] = sessionSecretStorage.get(key);
    }
    return data;
  },

  rem: (key) => {
    sessionStorage.removeItem(key);
  },

  clear: () => {
    sessionStorage.clear();
  },
};

// 多存储方式

export default ls;
